package com.zj.sa_token.controller;

import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;
import java.util.UUID;

@Api(tags = " 上传")
@CrossOrigin
@Controller
@RequestMapping("upload")
public class UploadController {

        @PostMapping("/image")
        @ResponseBody
        public String upFile(@RequestParam("file") MultipartFile file, Map map, HttpServletRequest request) {
            String path = "D:/upload";
            String fileName = file.getOriginalFilename();//获取文件名称
            String suffixName=fileName.substring(fileName.lastIndexOf("."));//获取文件后缀
            fileName= UUID.randomUUID()+suffixName;//重新生成文件名
            System.out.println(fileName);
            System.out.println("type::" + suffixName);
            System.out.println("filename::" + fileName);
            File targetFile = new File(path);
            if (!targetFile.exists()) {
                // 判断文件夹是否未空，空则创建
                targetFile.mkdirs();
            }
            File saveFile = new File(targetFile, fileName);
            try {
                //指定本地存入路径
                file.transferTo(saveFile);
                System.out.println("执行成功");
                String path1 = path + fileName;
                System.out.println(path1);
                //     return "success";
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("执行失败");
                return "failed";
            }
            map.put("img",fileName);//Java 集合类中的 Map.put() 方法将获取 Map 集合的所有键名，并存放在一个 Set 集合对象中。
            String path1 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String s = "upload/" + fileName;
            System.out.println(s);
            return s;
        }
        @GetMapping("/1")
        //前端html页面为ht.html
        public String header(){
            return "ht";
        }

}
